﻿using System.Collections.Generic;
using System.Linq;
using System;

namespace ChatService
{
    public class ChatService : IChatService
    {
        public IEnumerable<ChannelDTO> GetChanellsAll()
        {
            Telerik_ChatEntities context = new Telerik_ChatEntities();
            IEnumerable<Channel> channels;
            IEnumerable<ChannelDTO> channelsDTO;
            channels = from c in context.Channels
                                        orderby c.Name
                                        select c;

            channelsDTO = channels.Select(c => ChannelDTO.CreateFromChannel(c));
            return channelsDTO;
        }

        public IEnumerable<MessageDTO> GetMessagesInChannel(string channelName)
        {
            Telerik_ChatEntities context = new Telerik_ChatEntities();
            IEnumerable<MessageDTO> messagesDTO;
            IEnumerable<Message> messages = from m in context.Messages
                                            join c in context.Channels on m.ChannelID equals c.ChannelID
                                            where c.Name == channelName
                                            orderby m.Date 
                                            select m;

            messagesDTO = messages.Select(m => MessageDTO.CreateFromMessage(m));

            return messagesDTO;
        }

        public void PostMessage(Post post)
        {
            Telerik_ChatEntities context = new Telerik_ChatEntities();
            int channelId = (from c in context.Channels
                     where c.Name == post.ChannelName
                     select c.ChannelID).Single();

            Message message = new Message();
            message.Body = post.Body;
            message.Date = DateTime.Now;
            message.ChannelID = channelId;

            context.Messages.AddObject(message);
            context.SaveChanges();
            
        }
    }
}